package com.zxdemo.service.imp;

import java.util.Date;
import java.util.List;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.zxdemo.jpa.model.User;
import com.zxdemo.mybatis.dao.UserMapper;
import com.zxdemo.mybatis.dao.UserRoleMapper;
import com.zxdemo.service.UserService;

@Service("userService")
public class UserServiceImpl implements UserService{
	@Autowired
	private UserMapper userMapper;
	@Autowired
	private UserRoleMapper userRoleMapper;
	@Override
	public User queryByUserId(Long userId) {
		return userMapper.queryByUserId(userId);
	}

	@Override
	public User queryByUserName(String userName) {
		return userMapper.queryByUserName(userName);
	}

	@Override
	public List<User> queryList(int offset,int limit) {
		return userMapper.queryList(offset,limit);
	}

	@Override
	public int queryTotal() {
		return userMapper.queryTotal();
	}

	@Override
	public List<String> queryAllPerms(Long userId) {
		return userMapper.queryAllPerms(userId);
	}

	@Override
	public List<Long> queryAllMenuId(Long userId) {
		return userMapper.queryAllMenuId(userId);
	}

	@Override
	@Transactional
	public void save(User user) {
		user.setCreateTime(new Date());
		//sha256加密用户密码
		user.setUserPassword(new Sha256Hash(user.getUserPassword()).toHex());
		userMapper.save(user);
		//获取新建用户所选角色Id
		List<Long> roleIdList=user.getRoleIdList();
		//保存用户角色关系
		userRoleMapper.save(user.getUserId(), roleIdList);
		
		
	}

	@Override
	public void update(User user) {
		// TODO Auto-generated method stub
		//判断密码是否需要更改，若更改则启用sha256加密
		if(StringUtils.isBlank(user.getUserPassword())){
			user.setUserPassword(null);;
		}else{
			user.setUserPassword(new Sha256Hash(user.getUserPassword()).toHex());;
		}
		userMapper.update(user);
		//获取用户所选角色Id
		List<Long> roleIdList=user.getRoleIdList();
		//保存用户角色关系
		userRoleMapper.save(user.getUserId(), roleIdList);
		
	}

	@Override
	public int updatePassword(Long userId,String userPassword,String newPassword) {
		// TODO Auto-generated method stub
		//密码更改有问题，待解决
		return userMapper.updatePassword(userId,userPassword,newPassword);
	}

	@Override
	public int deleteBatch(Long[] userId) {
		// TODO Auto-generated method stub
		return userMapper.deleteBatch(userId);
	}

	@Override
	public List<User> queryListNoPage() {
		// TODO Auto-generated method stub
		return userMapper.queryListNoPage();
	}

	@Override
	public int deleteByUserId(long userId) {
		// TODO Auto-generated method stub
		return userMapper.deleteByUserId(userId);
	}
				
}
